<template lang="html">
  <article id="views-video">
    <section
      class="video-wrapper"
      :class="{ isFilter: !isFree }"
    >
      <VideoContent :detail="videoDetail"></VideoContent>
    </section>
    <Intro
      :detail="videoDetail"
      :class="{ isFilter: !isFree }"
    ></Intro>
    <Recommends
      :list="videoList"
      :class="{ isFilter: !isFree }"
    ></Recommends>

    <section class="modal-wrapper" style="z-index: 999" v-if="!isFree">
      <Modal :price="price" v-on:confirm="buyVideo"></Modal>
    </section>
  </article>
</template>

<script>
import superagent from 'superagent'
import authMiddleware from '@/lib/auth-middleware'
import utils from '@/lib/utils'

export default {
  components: {
    VideoContent: require('@/components/video/video'),
    Intro: require('@/components/video/intro'),
    Recommends: require('@/components/video/recommends'),
    Modal: require('@/components/video/modal')
  },
  data(){
    return {
      videoDetail: null,
      videoList: []
    }
  },
  computed: {
    isFree(){
      if(this.videoDetail !== null && !this.videoDetail.video_url){
        return false
      } else {
        return true
      }
    },
    price(){
      if(this.videoDetail !== null && !!this.videoDetail.price){
        return parseInt(this.videoDetail.price, 10)*0.01
      } else {
        return '0'
      }
    }
  },
  methods: {
    getInfo(){
      this.getVideoDetail()
      .then(data => {
        this.videoDetail = data.video
      })
      .catch(e => {
        console.warn(e);
      })

      this.getRecommendList()
      .then(data => {
        this.videoList = this.recommendListFilter(data, this.$route.params.video_id)
      })
    },
    getVideoDetail(){
      return new Promise((resolve, reject) => {
        superagent.get(`/api/video/show?videoId=${this.$route.params.video_id}`)
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body && !!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getVideoDetail error'))
              }
            }
          })
      })
    },
    getRecommendList(){
      return new Promise((resolve, reject) => {
        superagent.get('/api/video/index')
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data.videos)
            } else {
              if(!!res.body && !!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getRecommendList error'))
              }
            }
          })
      })
    },
    recommendListFilter(list, id){
      let result = list.filter(item => {
        return item.id != id
      })
      return result
    },
    buyVideo(){
      this.$store.dispatch('toggleIsLoading')
      this.getVideoOrder()
      .then(data => {
        return this.getPayParameter(data.orderId)
      })
      .then(result => {
        this.$store.dispatch('toggleIsLoading')
        let self = this
        result = result.paymentConfigs
        this.$store.dispatch('wxPay', {
          timestamp: result.timestamp,
          nonceStr: result.nonceStr,
          _package: result.package,
          signType: result.signType,
          paySign: result.paySign,

          callback: function(){
            utils.toast('支付成功')
            window.location.reload(true)
          }
        })
      })
      .catch(e => {
        this.$store.dispatch('toggleIsLoading')
        if(!!e && e.hasOwnProperty('errMsg')){
          utils.toast(e.errMsg)
        }
      })
    },
    getVideoOrder(){
      return new Promise((resolve, reject) => {
        superagent.get(`/api/video/buy/${this.$route.params.video_id}`)
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body && !!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getVideoOrder error'))
              }
            }
          })
      })
    },
    getPayParameter(orderId){
      return new Promise((resolve, reject) => {
        superagent.get(`/api/WxCommon/payOrder/${orderId}?type=video`)
          .use(authMiddleware())
          .end((err, res) => {
            if(res.ok){
              resolve(res.body.data)
            } else {
              if(!!res.body.data){
                reject(res.body.data)
              } else {
                reject(new Error('getPayParameter error'))
              }
            }
          })
      })
    },
  },
  created(){
    this.getInfo()
  },
  beforeRouteEnter(to, from, next){
    let result = utils.checkLocator()
    if(typeof result === 'string'){
      if(window.location.hash !== `#${to.path}`){//判断进入该路由的方法为app内路由跳转还是绝对地址跳转
        result = result.replace(`#${from.path}`, `#${to.path}`)
      }
      window.location.replace(result)//video页与confirm页存在一个为了补充？符号的重定向，因此这个重定向需要使用replace方法去除当前页面的访问历史
    } else {
      next()
    }
  },
  beforeRouteUpdate(to, from, next){
    next()
    this.updateWxConfig()
    this.getInfo()
  }
}
</script>

<style lang="scss" scoped>
@import "../css/config";
.isFilter{
  filter: blur(6px);
}
#views-video{
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
  padding: $video-height 22px 20px;
  background-color: $common-black;
  .video-wrapper{
    position: fixed;
    z-index: 990;
    top: 0;
    left: 0;
    width: 100%;
    height: $video-height;
    background-color: #fff;
  }
  .modal-wrapper{
    position: fixed;
    top: 0;
    left: 0;
    z-index: 999;
    width: 100%;
    height: 100%;
    overflow: hidden;
    background-color: transparent;
  }
}
</style>
